package malus.shaofeng.com.beiwomusic.utils;

import android.content.Context;
import android.content.SharedPreferences;

import malus.shaofeng.com.beiwomusic.model.LoginUser;

/**
 * 辅助存储本地用户信息
 */
public class UserHelper  {
    private static Context context;
    private static UserHelper instance;
    private UserHelper(Context context){
        this.context=context;
    }
    public static UserHelper getInstance(){
        if(context==null){
            throw new IllegalArgumentException("userHelper must init before use");
        }
        return instance;
    }
    public static void initUserHelper(Context context){
        if(context==null){
            throw new IllegalArgumentException("context must not null");
        }
        instance=new UserHelper(context);

    }

    /**
     * 存储用户信息到sharePreferces
     * @param user
     */
    public void setUser(LoginUser user){
        SharedPreferences sp = context.getSharedPreferences(
                Constants.SP.KEY_SP_TABLE_LOGIN_USER
                , Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("account", user.getAccount());
        edit.putString("city", user.getCity());
        edit.putString("nickname",user.getNickname());
        edit.putString("provice", user.getProvince());
        edit.putString("faceUri", user.getFace_uri());
        edit.putInt("author", user.getAuthor());
        edit.putInt("cityId", user.getCity_id());
        edit.putLong("userId", user.getUser_id());
        edit.putInt("modifyFace", user.getModify_face());
        edit.putInt("sex",user.getSex());
        edit.putString("password",user.getPassword());
        edit.commit();
    }

    /**
     * 用手机中获取用户信息
     * @return 返回用户信息，如果返回null则表示没有该用户
     */
    public LoginUser getUser(){
        LoginUser user=new LoginUser();
        SharedPreferences sp = context.getSharedPreferences(
                Constants.SP.KEY_SP_TABLE_LOGIN_USER
                , Context.MODE_PRIVATE);
        user.setUser_id(sp.getLong("userId",0));

        user.setSex(sp.getInt("sex", 0));
        user.setFace_uri(sp.getString("faceUri", ""));
        user.setNickname(sp.getString("nickname", ""));
        user.setAccount(sp.getString("account", ""));
        user.setAuthor(sp.getInt("author", 0));
        user.setProvince(sp.getString("provice", ""));
        user.setCity(sp.getString("city", ""));
        user.setCity_id(sp.getInt("cityId", 0));
        user.setModify_face(sp.getInt("modifyFace", 0));
        user.setPassword(sp.getString("password",""));
        return user;
    }
}
